<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/27
 * Time: 17:10
 */

namespace app\index\controller;
use think\Db;
class Dig extends Base{
    protected $userId;
    public function _initialize(){
        parent::_initialize();
        $this->userId=cookie('user_id');
    }
    // 挖矿首页，显示用户购买的旷工，并进行挖矿操作
    public function index(){
        $field='worker_id,make,current_income,estimated_income';
        $dig=Db::name('user_worker')->where('user_id',$this->userId)->where('is_full=0')->distinct(true)->field($field)->select();
        $res=Db::name('collect_dig')->where('user_id',$this->userId)->whereTime('add_time','today')->find();
        $digMoney=$dig;
        if (!is_null($res)){
            $digMoney=[];
        }
        // 今天购买的旷工
        $todayBuy=Db::name('user_worker')->where('user_id',$this->userId)->field('worker_id')->whereTime('add_time','today')->select();
        $ids=[];
        foreach ($todayBuy as $key => $value){
            array_push($ids,$value['worker_id']);
        }
        foreach ($dig as $key => $value){
            if ($value['current_income'] > $value['estimated_income']){
                unset($dig[$key]);
            }
        }
        foreach ($digMoney as $key => $value){
            if (in_array($value['worker_id'],$ids)){
                unset($digMoney[$key]);
            }
        }
        $this->assign([
            'dig' => $dig,
            'digMoney' => $digMoney,
        ]);
        return view();
    }
    // 收矿
    public function collectDig(){
        $res=Db::name('collect_dig')->where('user_id',$this->userId)->whereTime('add_time','today')->find();
        if (!is_null($res)){
            return json(['msg' => '今日已收取','code' => -1]);
        }
        $field='make,worker_id,id,current_income,estimated_income';
        $worker=Db::name('user_worker')->where('user_id',$this->userId)->field($field)->where('is_full=0')->select();
        $collectMoney=0;
        $data=[];
        foreach ($worker as $key => $value){
            array_push($data,[
                'user_id' => $this->userId, 'add_time'=> time(),'reward'=>$value['make'],/*产能多少*/'worker_id' => $value['worker_id']
            ]);
            Db::name('user_worker')->where('id',$value['id'])->setInc('current_income',$value['make']);
            $collectMoney+=$value['make'];
            if ($value['current_income']+$value['make'] >= $value['estimated_income']){
                Db::name('user_worker')->where('id',$value['id'])->update(['is_full' => 1,'full_time' => time()]);
            }
        }
        Db::name('collect_dig')->insertAll($data);
        Db::name('account_detail')->insert(['user_id'=>$this->userId,'add_time'=>time(),'money'=>$collectMoney,'remark' => '挖矿收益',]);
        Db::name('users')->where('id',$this->userId)->setInc('money',$collectMoney);
        return json(['msg' => '收取成功' ,'code' => 1]);
    }
}